    //
//  AppsViewController.m
//  SnowCovered
//
/*
 
 Copyright (c) 2010, Subodh Shakya, Anand Subba Rao, All Rights Reserved
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 
 */
#import "AppsViewController.h"
#import "AppDataController.h"
#import "ProductTableViewCell.h"
#import "Product.h"

@interface AppsViewController()
@property (nonatomic, retain) NSArray* topApps;
@property (retain) NSMutableDictionary* appIcons;
@property (retain) NSMutableDictionary* imageDownloadsInProgress;

- (void)loadImagesForOnscreenRows;
- (void)startIconDownloadForIndexPath:(NSIndexPath *)indexPath imageUrlString:(NSString*)url;
@end


@implementation AppsViewController
@synthesize appsTableView;
@synthesize dataController;
@synthesize topApps;
@synthesize appIcons;
@synthesize imageDownloadsInProgress;


enum {
    AppsSection = 0,
    MaxSections = 1
};

/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataController = [AppDataController sharedController];
    self.appIcons = [NSMutableDictionary dictionary];
    self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
}


/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    self.appsTableView = nil;
    self.dataController = nil;
    self.appIcons = nil;
    self.imageDownloadsInProgress = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self registerForNotifications];
    
    if([self.topApps count] == 0) {
        [self startLoadingData];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    NSIndexPath* selectedRow = nil;
    if (selectedRow = [self.appsTableView indexPathForSelectedRow]) {
        [self.appsTableView deselectRowAtIndexPath:selectedRow animated:animated];
    }
    
    [self.appsTableView flashScrollIndicators];
}

- (void)dealloc {
    self.topApps = nil;
    [super dealloc];
}

#pragma mark -
#pragma mark TableView Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return MaxSections;
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    NSInteger rows = 0;
    
    switch (section) {
        case AppsSection:
            rows = [self.topApps count];
            break;
        default:
            break;
    }
    
    return rows;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* reuseIdentifier = @"productCell";
    static NSString* firstCellIdentifier = @"firstCell";

    
    ProductTableViewCell* cell = nil;
    
    if (indexPath.row == 0) {
        cell = (ProductTableViewCell*)[tableView dequeueReusableCellWithIdentifier:firstCellIdentifier];
        if (cell == nil) {
            cell = [[ProductTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                               reuseIdentifier:firstCellIdentifier];
            [cell autorelease];
        }
    } else {
        cell = (ProductTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (cell == nil) {
            cell = [[ProductTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                               reuseIdentifier:reuseIdentifier];            
            [cell autorelease];
        }
    }
    
    if (indexPath.row == 0) {
        cell.featured = YES;
    } else {
        cell.featured = NO;
    }
    
    Product* product = [self.topApps objectAtIndex:indexPath.row];
    cell.product = product;
    
    UIImage* appIcon = [self.appIcons objectForKey:indexPath];
    if (!appIcon) {
        if (self.appsTableView.dragging == NO && self.appsTableView.decelerating == NO) {
            [self startIconDownloadForIndexPath:indexPath imageUrlString:product.imageURL];
        }
        // if a download is deferred or in progress, return a placeholder image
        cell.productImage.image = [UIImage imageNamed:@"gray_40x40.png"];                
    } else {
        cell.productImage.image = appIcon;
    }
    
    
    cell.productName.text = cell.product.productName;
    cell.publisherName.text = cell.product.publisherName;
//    cell.productPrice.text = [NSString stringWithFormat:@"$%@",cell.product.price];
//    cell.publishedDate.text = [NSDateFormatter localizedStringFromDate:product.publishedDate
//                                                             dateStyle:NSDateFormatterMediumStyle
//                                                             timeStyle:NSDateFormatterNoStyle];
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) 
        return [ProductTableViewCell requiredFeatureHeight];
    
    return [ProductTableViewCell requiredHeight];
}

#pragma mark -
#pragma mark Tableview Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark Table cell image support

- (void)startIconDownloadForIndexPath:(NSIndexPath *)indexPath imageUrlString:(NSString*)url {
    if ([url length] <= 0) 
        return;
    
    IconDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:indexPath];
    if (iconDownloader == nil) {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.indexPathInTableView = indexPath;
        iconDownloader.imgUrlString = url;
        iconDownloader.delegate = self;
        [self.imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
        [iconDownloader release];   
    }
}

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows {
    if ([self.topApps count] > 0) {
        NSArray *visiblePaths = [self.appsTableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths) {
            UIImage* appIcon = [self.appIcons objectForKey:indexPath];
            if (appIcon == nil) {// avoid the app icon download if the app already has an icon 
                Product* p = [self.topApps objectAtIndex:indexPath.row];
                [self startIconDownloadForIndexPath:indexPath imageUrlString:p.imageURL];
            }
        }
    }
}

// called by our ImageDownloader when an icon is ready to be displayed
- (void)appImageDidLoad:(NSIndexPath *)indexPath scaledImage:(UIImage*)scaledImage{
    IconDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:indexPath];
    if (iconDownloader != nil) {
        ProductTableViewCell *cell = (ProductTableViewCell*)[self.appsTableView cellForRowAtIndexPath:iconDownloader.indexPathInTableView];
        
        // Display the newly loaded image
        cell.productImage.image = scaledImage;
        [self.appIcons setObject:scaledImage forKey:indexPath];
    }
}


#pragma mark -
#pragma mark Deferred image loading (UIScrollViewDelegate)

// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self loadImagesForOnscreenRows];
}


#pragma mark -
- (void)loadingApps:(NSNotification*)aNotif {
    Category* cat = [aNotif object];
    
    if ([self isMyCategory:cat]) {
        if ([aNotif.name isEqual:[self progressNotification]]) {
            self.topApps = nil;
            [self performSelectorOnMainThread:@selector(transitionToLoading)
                                   withObject:nil
                                waitUntilDone:NO];
        } else {
            self.topApps = [self appsList:[aNotif userInfo]];
            
            [self performSelectorOnMainThread:@selector(transitionToTable)
                                   withObject:nil
                                waitUntilDone:NO];
        }
    }
}

- (void)transitionToTable {
    if ([self.appsTableView superview] == nil) {
        [self.view addSubview:self.appsTableView];
        [self.appsTableView reloadData];
    }
}

- (void)transitionToLoading {
    if ([self.appsTableView superview])
        [self.appsTableView removeFromSuperview];
}

- (BOOL)isMyCategory:(Category *)cat {
    return NO;
}

- (void)startLoadingData {
}

- (void)registerForNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loadingApps:)
                                                 name:LoadingTopApps
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loadingApps:)
                                                 name:FailedLoadingTopApps
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loadingApps:)
                                                 name:FinishedLoadingTopApps
                                               object:nil];
}

- (NSString*)progressNotification {
    return LoadingTopApps;
}

- (NSArray*)appsList:(NSDictionary*)userInfo {
    return [userInfo valueForKey:@"topApps"];
}
@end